﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Site.Models
{
    public class MessageRepository : IMessageRepository
    {
        private BMSiteDBEntities _db = new BMSiteDBEntities();
        public IEnumerable<Message> GetReceivedMessages()
        {
            return (from m in _db.Message
                    where m.Receiver == HttpContext.Current.User.Identity.Name
                    select m).ToList();
        }
        public IEnumerable<Message> GetSentMessages()
        {
            return (from m in _db.Message
                    where m.Sender == HttpContext.Current.User.Identity.Name
                    select m).ToList();
        }
        public Message GetMessageById(Guid id)
        {
            return (from m in _db.Message
                    where m.MessageId == id
                    select m).FirstOrDefault();
        }

        public bool NewMessage(Message message)
        {

            _db.AddObject("Message", message);
            _db.SaveChanges();
            return false;
        }

        public bool IsMember(string name)
        {
            if ((from u in _db.aspnet_Users
                 where u.UserName == name
                 select u.UserId) != null)
            {
                return true;
            }
            else
                return false;

        }

        public void ReadMessage(Guid messageId)
        {
            var message = GetMessageById(messageId);
            message.Read = true;
            message.ReadDate = DateTime.Now;
            _db.SaveChanges();

        }


    }
}